package com.mutouren.modules.datapush;

import javax.annotation.Resource;

import com.mutouren.common.log.LogAlias;
import com.mutouren.common.log.LogManager;
import com.mutouren.common.log.Logger;
import com.mutouren.common.utils.JsonUtils;
import com.mutouren.modules.datapush.base.DataPushLogAlias;
import com.mutouren.modules.datapush.base.PushDubboServer;
import com.mutouren.modules.datapush.base.PushMessage;

public class PushDubboServerImpl implements PushDubboServer {
	
	private final static Logger errorLogger = LogManager.getLogger(LogAlias.SystemError.name());
	private final static Logger ReceiveLogger = LogManager.getLogger(DataPushLogAlias.DataPushReceive.name());
	
	@Resource
	private ServerProxy serverProxy;	

	@Override
	public boolean receive(PushMessage message) {
		boolean isException = false;
		boolean isReceive = false;

		try {			
			isReceive = serverProxy.receive(message);
			return isReceive;
		} catch (Throwable t) {
			isException = true;
			errorLogger.error("PushDubboServer receive error", t);
			throw t;
		} finally {
			writeReceiveLog(isReceive, isException, JsonUtils.beanToJson(message));
		}
	}

	@Override
	public boolean receive(byte[] messagePackage) {
		boolean isException = false;
		boolean isReceive = false;
		
		try {			
			PushMessage message = PushMessage.decode(messagePackage);	
			isReceive = serverProxy.receive(message);
			return isReceive;
		} catch (Throwable t) {
			isException = true;
			errorLogger.error("PushDubboServer receive error", t);
			throw t;
		} finally {
			writeReceiveLog(isReceive, isException, new String(messagePackage));
		}

	}
	
	private static void writeReceiveLog(boolean isReceive, boolean isException, String content) {		
		String log = String.format("isReceive=%s,isException=%s,content=%s", isReceive, isException, content);
		ReceiveLogger.info(log);
	}	

}
